//
//  XPEmojiKeyboardToolBar.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/20.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

enum XPToolBarButtonSelectedType: Int {
    case Normal = 0
    case Emoji
    case Lxh
}

class XPEmojiKeyboardToolBar: UIStackView {
    
    var selectedButton: UIButton?
    var selectedButtonClosure: ((type: XPToolBarButtonSelectedType)->())?
    
    /// 滚动表情键盘时自动选择按钮的方法
    func autoSelectButton(section: Int) -> Void {
        let button = subviews[section] as! UIButton
        selectButton(button)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        axis = .Horizontal
        distribution = .FillEqually
        addButton("默认",type: .Normal)
        addButton("Emoji", type: .Emoji)
        addButton("浪小花", type: .Lxh)
        autoSelectButton(0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func addButton(title: String, type: XPToolBarButtonSelectedType) {
        let button = UIButton()
        button.addTarget(self, action: #selector(XPEmojiKeyboardToolBar.buttonSelected(_:)), forControlEvents: .TouchDown)
        button.tag = type.rawValue
        button.adjustsImageWhenHighlighted = false
        button.setTitle(title, forState: .Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_left_selected"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_left_normal"), forState: .Selected)
        addArrangedSubview(button)
    }
    
    @objc private func buttonSelected(button: UIButton) {
        selectButton(button)
        let buttonType = XPToolBarButtonSelectedType(rawValue: button.tag)!
        selectedButtonClosure?(type: buttonType)
    }
    
    private func selectButton(button: UIButton) {
        if button.selected { return }
        selectedButton?.selected = false
        button.selected = true
        selectedButton = button
    }
}


